package service

import (
	"helloword01/23customerprac/model"
)

type CustomerService struct {
	//定义一个客户切片,可以存放客户信息
	customers []*model.Customer

	//定义客户的实际个数
	customerNum int
}

// GenerateCustomerService 先创建一个Customer对象,放到 CustomerService的Customers切片中
// 作为测试数据
func GenerateCustomerService() *CustomerService {
	//创建一个CustomerService实例
	customerService := &CustomerService{}
	//调用方法-创建一个客户实例
	customer := model.GenerateCustomerWithoutId("张三", "男", 10, "999", "zs@sohu.com")
	id := customerService.customerNum + 1
	customer.Id = id

	//放入切片中
	customerService.customers = append(customerService.customers, customer)
	//个数
	customerService.customerNum = len(customerService.customers)
	//return
	return customerService
}

// List 返回客户的信息数组
func (cs *CustomerService) List() []*model.Customer {
	return cs.customers
}

// Add 完成添加客户的功能
func (cs *CustomerService) Add(customer *model.Customer) bool {
	//这时我们可以这个customer一个id
	customer.Id = cs.customerNum + 1
	cs.customers = append(cs.customers, customer)
	cs.customerNum = len(cs.customers)
	return true

}

// Delete 删除一个客户
func (cs *CustomerService) Delete(id int) bool {
	//先根据id去得到该id的客户对应元素下标
	index := cs.FindIndexById(id)

	if index == -1 {
		return false
	}
	//找到，删除切片对应的index的元素
	cs.customers = append(cs.customers[:index], cs.customers[index+1:]...)
	cs.customerNum = len(cs.customers)
	return true

}

// FindIndexById FindById 先根据id去得到该id的客户对应元素下标
// 如果找到就返回对应的下标，如果找不到，我们返回-1
func (cs *CustomerService) FindIndexById(id int) int {
	index := -1
	for i := 0; i < cs.customerNum; i++ {
		if cs.customers[i].Id == id {
			index = i
			break
		}
	}
	return index
}

// FindCustomerById 根据id查询客户
func (cs *CustomerService) FindCustomerById(id int) *model.Customer {
	for _, customer := range cs.customers {
		if customer.Id == id {
			return customer
		}
	}
	return nil

}

// GetCustomerIds 获取客户ids
func (cs *CustomerService) GetCustomerIds() []int {
	var ids []int
	for _, customer := range cs.customers {
		ids = append(ids, customer.Id)
	}
	return ids
}
